package com.qingcheng.service.impl;

import com.qingcheng.dao.SkuMapper;
import com.qingcheng.dao.StockBackMapper;
import com.qingcheng.pojo.goods.StockBack;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.StockBackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class StockBackServiceImpl implements StockBackService {

    @Autowired(required = false)
    private StockBackMapper stockBackMapper;

    @Override
    @Transactional
    public void addList(List<OrderItem> orderItems) {
        for (OrderItem orderItem : orderItems) {
            StockBack stockBack=new StockBack();
            stockBack.setOrderId(orderItem.getOrderId());
            stockBack.setSkuId(orderItem.getSkuId());
            stockBack.setStatus("0");
            stockBack.setNum(orderItem.getNum());
            stockBack.setCreateTime(new Date());
            stockBackMapper.insert(stockBack);
        }
    }

    @Autowired(required = false)
    private SkuMapper skuMapper;

    @Override
    @Transactional
    public void doBack() {
        System.out.println("库存回滚任务开始");
        //查询库存回滚表中状态为0的记录
        StockBack stockBack = new StockBack();
        stockBack.setStatus("0");
        List<StockBack> stockBacks = stockBackMapper.select(stockBack);

        for (StockBack back : stockBacks) {
            System.out.println("开始回滚库存");
            //添加库存
//            skuMapper.deductionStock(back.getSkuId(),-back.getNum());
//            //减少销量
//            skuMapper.addSaleNum(back.getSkuId(),-back.getNum());
            back.setStatus("1");
            back.setBackTime(new Date());
            stockBackMapper.updateByPrimaryKeySelective(back);
            System.out.println("库存回滚成功");
        }
    }
}
